package com.hm.service.framework.session;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.hm.service.framework.crypto.CBC.AES_CBC;
import com.hm.service.framework.crypto.KeyConstant;

import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;


public class SessionUtils {
    //默认有效期是24小时
    public static final long SURVIVAL_TIME = 1000 * 60 * 60 * 24;

    //生成sessionId
    public static String generateId() {
        SessionBean sessionBean = new SessionBean();
        sessionBean.setIssuer("hm");
        sessionBean.setSecretKeyGroupVersion(KeyConstant.SecretKeyVersion);
        sessionBean.setIssueTime(System.currentTimeMillis());//发行时间
        String str = JSON.toJSONString(sessionBean);
        //采用CBC加密模式增加偏移量
        return AES_CBC.encrypt(KeyConstant.SessionSecretKey, KeyConstant.SessionIvParameter, str);
    }

    //验证sessionId
    public static HashMap<String, String> verifier(String sessionId) {
        HashMap<String, String> resMap = new HashMap<>();
        try {
            String decrypt = AES_CBC.decrypt(KeyConstant.SessionSecretKey, KeyConstant.SessionIvParameter, sessionId);
            SessionBean sessionBean = JSONObject.parseObject(decrypt, SessionBean.class);
            //判断时间是否超时
            long issueTime = sessionBean.getIssueTime();
            long timeDifference = calculateTimeDifference(issueTime, System.currentTimeMillis());
            if (timeDifference > SURVIVAL_TIME) {
                //颁发时间到了
                resMap.put("state", "1");
                resMap.put("msg", "session过期了");
            } else {
                resMap.put("state", "0");
                resMap.put("msg", "验证通过");
                resMap.put("version", sessionBean.getSecretKeyGroupVersion());
            }
        } catch (Exception e) {
            resMap.put("state", "2");
            resMap.put("msg", "验证异常：" + e.getMessage());
        }
        return resMap;
    }

    private static long calculateTimeDifference(long timestamp1, long timestamp2) {
        // 将时间戳转换为Instant对象
        Instant instant1 = Instant.ofEpochMilli(timestamp1);
        Instant instant2 = Instant.ofEpochMilli(timestamp2);
        // 计算时间差并返回结果（单位：毫秒）
        Duration duration = Duration.between(instant1, instant2);
        return duration.toMillis();
    }
}
